package com.hunnyhu.tools;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextPaint;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	private long mExitTime = 0;
	protected SignDao signDao;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_activity);
		TextView checkInfo = (TextView) findViewById(R.id.checkInInfo);
		TextPaint tp = checkInfo.getPaint();
		tp.setFakeBoldText(true);
		checkInfo.setText(currentDate());
		Button checkIn = (Button) findViewById(R.id.checkIn);
		Button checkOut = (Button) findViewById(R.id.checkOut);
		checkIn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Date checkInDate = new Date();
				String msg = null;
				List<Map<String, Object>> o = getSignDao().findByCheckInDate(checkInDate);
				if (null == o || o.isEmpty()) {
					msg = String.format("%1$tY年%1$tb月%1$td日 %1$tA %1$tT ",
							checkInDate) + getResources().getString(R.string.check_in);
					if (getSignDao().checkIn(checkInDate) > 0) {
						updateDetails(checkInDate);
						msg += "成功。";
					} else {
						msg += "失败。";
					}
				} else {
					msg = "你今天已经签到啦，编辑请到列表！";
				}
				makeText(msg);
			}
		});
		checkOut.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Date checkOutDate = new Date();
				String msg = null;
				List<Map<String, Object>> o = getSignDao().findByCheckOutDate(checkOutDate);
				if (null == o || o.isEmpty()) {
					msg = String.format("%1$tY年%1$tb月%1$td日 %1$tA %1$tT ",
							checkOutDate) + getResources().getString(R.string.check_out);
					if (getSignDao().checkOut(checkOutDate) > 0) {
						updateDetails(checkOutDate);
						msg += "成功。";
					} else {
						msg += "失败。";
					}
				} else {
					msg = "你今天已经签退啦，编辑请到列表！";
				}
				makeText(msg);
			}
		});
	}
	
	protected void onResume() {
		super.onResume();
		updateDetails(new Date());
	}
	
	protected void updateDetails(Date date) {
		TextView checkDetails = (TextView)findViewById(R.id.checkDetails);
		Map<String, Object> map = getSignDao().findByDate(date);
		String begin = (null == map ? null : (String)map.get(DBHelper.C_DATE_BEGIN));
		String end = (null == map ? null: (String)map.get(DBHelper.C_DATE_END));
		String checkIn = (null == begin) ? "暂无信息" : begin;
		String checkOut = (null == end) ? 
				"暂无信息" : end;
		if (null != begin && null != end) {
			ImageView imageView = (ImageView)findViewById(R.id.checkImage);
			imageView.setImageResource(R.drawable.check_status_ok);
		}
		StringBuffer signInfo = new StringBuffer();
		signInfo.append("签到时间: ");
		signInfo.append(checkIn);
		signInfo.append("\n");
		signInfo.append("签退时间: ");
		signInfo.append(checkOut);
		TextPaint tp = checkDetails.getPaint();
		tp.setFakeBoldText(true);
		checkDetails.setText(signInfo.toString());
		TextView checkLogs = (TextView)findViewById(R.id.checkLogs);
		if (null == map || null == map.get(DBHelper.C_ID)) {
			checkLogs.setVisibility(View.GONE);
		} else {
			String dateCreated = (null == map.get(DBHelper.C_DATE_CREATED) ? 
					"暂无信息" : (String)map.get(DBHelper.C_DATE_CREATED));
			String lastUpdated = (null == map.get(DBHelper.C_LAST_UPDATED) ? 
					"暂无信息" : (String)map.get(DBHelper.C_LAST_UPDATED));
			StringBuffer logInfo = new StringBuffer();
			logInfo.append("记录时间: ");
			logInfo.append(dateCreated);
			logInfo.append("\n");
			logInfo.append("更新时间: ");
			logInfo.append(lastUpdated);
			checkLogs.setText(logInfo.toString());
		}
		
	}
	
	protected SignDao getSignDao() {
		if (null == signDao) {
			signDao = new SignDao(this);
		}
		return signDao;
	}

	protected Context getContext() {
		return this;
	}
	
	protected void makeText(String msg) {
		Toast.makeText(
				getContext(), msg, Toast.LENGTH_SHORT).show();
	}

	protected String currentDate() {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		String sDate = String.format("%1$tY年" + (calendar.get(Calendar.MONTH) + 1) + "月%1$td日 %1$tA",
				calendar.getTime());
		sDate += " 第" + calendar.get(Calendar.DAY_OF_YEAR) + "天 ";
		sDate += calendar.get(Calendar.WEEK_OF_YEAR) + "周";
		return sDate;
	}

	/**
	 * 创建选项菜单的方法
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.list:
			Intent intent = new Intent();  
			intent.setClass(MainActivity.this, XListViewActivity.class);  
			startActivity(intent);
			break;
		case R.id.about:
			makeDialog("滴咔.\nMade in China. \nBy Hunny.Hu.\nEmail:huxiong888@163.com");
			break;
		case R.id.exit:
			exit();
			break;
		}
		return true;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if ((System.currentTimeMillis() - mExitTime) > 2000) {
				Toast.makeText(getBaseContext(), "再按一次退出", Toast.LENGTH_SHORT)
						.show();
				mExitTime = System.currentTimeMillis();
			} else {
				exit();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	protected void makeDialog(String msg) {
		View view = LayoutInflater.from(getContext()).inflate(R.layout.mydialog, null);  
        TextView tv_text = (TextView) view.findViewById(R.id.dialog_textview_text);  
        tv_text.setText(msg);
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);  
        final AlertDialog dialog = builder.setView(view).create();  
        dialog.show();
        view.findViewById(R.id.dialog_textview_ok).setOnClickListener(new OnClickListener() {  
            @Override  
            public void onClick(View arg0) {  
                dialog.dismiss();  
            }  
        }); 
	}
	
	protected void exit() {
		finish();
		System.exit(0);
	}

}
